#include    "ActionMap.h"

// File [alfs/gui/ActionMap.cpp].
//
// ActionMap.
//
// An ActionMap associates UserCommand::Id's with actions.
//
// (c) copyright Alf P. Steinbach 2008.
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php>.

namespace alfs{

#define ThisClass   ActionMap

    ThisClass::ThisClass()
    {}

    ThisClass::ThisClass( InvocableUserCommandTree::Ptr commands )
    {
        if( !commands.isVoid() ) { copyActionsFrom( commands ); }
    }

    void ThisClass::swap( ThisClass& other )
    {
        myMap.swap( other.myMap );
    }

    void ThisClass::clear()
    {
        Map().swap( myMap );
    }

    void ThisClass::setActionFor( UserCommand::Id commandId, InvocableUserCommand::Action action )
    {
        myMap[commandId] = action;
    }

    void ThisClass::copyActionsFrom( InvocableUserCommandTree::Ptr commands )
    {
        typedef InvocableUserCommandTree::Iterator  Iter;

        for( Iter it = commands->begin();  it != commands->end();  ++it )
        {
            if( it->isCommand() )
            {
                InvocableUserCommand::Ptr const cmd = it->command();
                myMap[cmd->id()] = cmd->action();
            }
            else
            {
                copyActionsFrom( it->tree() );
            }
        }
    }

    InvocableUserCommand::Action ThisClass::actionFor( UserCommand::Id id ) const
    {
        Map::const_iterator const it  = myMap.find( id );
        return (it == myMap.end()? InvocableUserCommand::noAction : it->second);
    }

#undef  ThisClass

}  // alfs
